<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文章标题" prop="contentTitle">
        <el-input
          v-model="queryParams.contentTitle"
          placeholder="请输入文章标题"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关键字" prop="contentKeyword">
        <el-input
          v-model="queryParams.contentKeyword"
          placeholder="请输入关键字"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文章作者" prop="contentAuthor">
        <el-input
          v-model="queryParams.contentAuthor"
          placeholder="请输入文章作者"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:config:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:config:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:config:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:config:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefreshCache"
          v-hasPermi="['system:config:remove']"
        >刷新缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList"   @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="文章主键" align="center" prop="id" />
        <el-table-column label="所属栏目名称" align="center" prop="cmsCategory.categoryTitle" :show-overflow-tooltip="true" />
        <el-table-column label="文章标题" align="center" prop="contentTitle" :show-overflow-tooltip="true" />
        <el-table-column label="关键字" align="center" prop="contentKeyword" :show-overflow-tooltip="true"/>
        <el-table-column label="描述" align="center" prop="contentDescription" :show-overflow-tooltip="true"/>
        <el-table-column label="文章来源" align="center" prop="contentSource" :show-overflow-tooltip="true"/>


        <el-table-column label="文章作者" align="center" prop="contentAuthor" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="文章缩略图" width="100">
          <template slot-scope="scope">
            <el-image v-if="scope.row.contentImg" style="width: 100px; height: 100px" :src="scope.row.contentImg" fit="fit" />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:config:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:config:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
<!--        <el-form-item label="所属栏目" prop="configName">-->
<!--          <el-input v-model="form.configName" placeholder="请选择所属栏目" />-->
<!--        </el-form-item>-->
        <el-form-item label="所属栏目" prop="cmsCategory">
          <el-select v-model="form.cmsCategory">
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.categoryTitle"
              :value="item.id"
              :clearable=true
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章标题" prop="contentTitle">
          <el-input v-model="form.contentTitle" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章内容" prop="contentDetails">
          <el-input v-model="form.contentDetails"  type="textarea" :value="form.contentDetails" placeholder="请输入文章内容" />
        </el-form-item>
        <el-form-item label="关键字" prop="contentKeyword">
          <el-input v-model="form.contentKeyword" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item label="描述" prop="contentDescription">
          <el-input v-model="form.contentDescription" placeholder="请输入文章描述" />
        </el-form-item>
        <el-form-item label="文章略缩图" prop="contentImg">
<!--          <el-input v-model="form.contentImg" placeholder="请选择文章略缩图" />-->
          <el-upload
            class="avatar-uploader"
            action="http://localhost:10010/api/upload/image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.contentImg" :src="form.contentImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章来源" prop="contentSource">
          <el-input v-model="form.contentSource" placeholder="请输入文章来源" />
        </el-form-item>
        <el-form-item label="文章作者" prop="contentAuthor">
          <el-input v-model="form.contentAuthor" placeholder="请输入文章作者" />
        </el-form-item>
        <el-form-item label="是否显示" prop="contentDisplay">
          <template>
            <el-radio v-model="form.contentDisplay" label="0">是</el-radio>
            <el-radio v-model="form.contentDisplay" label="1">否</el-radio>
          </template>
        </el-form-item>
<!--        <el-form-item label="是否显示" prop="contentDisplay">-->
<!--          <el-radio-group v-model="form.contentDisplay">-->
<!--            <el-radio-->
<!--              v-for="dict in dict.type.sys_yes_no"-->
<!--              :key="dict.value"-->
<!--              :label="dict.value"-->
<!--            >{{dict.label}}</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConfig , refreshCache } from "@/api/system/config";
import { list,getConfig ,addConfig ,updateConfig, delConfig} from "@/api/tzxm/content";
import {optionselect,getDept} from "@/api/tzxm/category";


export default {
  name: "Config",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      //栏目名称
      typeOptions:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contentTitle: undefined,
        contentKeyword: undefined,
        contentAuthor: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cmsCategory: [
          { required: true, message: "所属栏目不能为空", trigger: "blur" }
        ],
        contentTitle: [
          { required: true, message: "文章标题不能为空", trigger: "blur" }
        ],
        contentDetails: [
          { required: true, message: "文章内容不能为空", trigger: "blur" }
        ],
        contentDescription: [
          { required: true, message: "文章描述不能为空", trigger: "blur" }
        ],
        contentImg: [
          { required: true, message: "文章略缩图不能为空", trigger: "blur" }
        ],
        contentAuthor: [
          { required: true, message: "文章作者不能为空", trigger: "blur" }
        ],
        contentDisplay: [
          { required: true, message: "文章是否显示不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getTypeList();
  },
  methods: {
    /** 查询栏目类型列表 */
    getTypeList() {
      optionselect().then(response => {
        this.typeOptions = response.data;
      });
    },

    /** 查询参数列表 */
    getList() {
      this.loading = true;
      list(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.configList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    handleAvatarSuccess(res, file) {
      console.log("==========",res)
      this.form.contentImg = res.data.url
      // this.form.album = URL.createObjectURL(file.raw);
    },
    // 上传图片之前的验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、PNG 格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
      }
      return isJPG && isLt1M
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        cmsCategory: undefined,
        categoryTitle: undefined,
        configName: undefined,
        contentTitle: undefined,
        contentDetails: undefined,
        contentKeyword: undefined,
        contentDescription: undefined,
        contentSource: undefined,
        contentAuthor: undefined,
        contentDisplay: "0",
        contentImg: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章管理";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const configId = row.id || this.ids
      getConfig(configId).then(response => {
        this.form = response.data;
        this.form.cmsCategory=response.data.cmsCategory.id
        this.open = true;
        this.title = "修改文章管理";
      });
    },
    /** 提交按钮 */
    // submitForm: function() {
    //   this.$refs["form"].validate(valid => {
    //     this.upType();
    //     console.log("执行后===================",this.form.cmsCategory);
    //     if (valid) {
    //       if (this.form.id != undefined) {
    //         updateConfig(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addConfig(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    submitForm: function() {
      this.$refs["form"].validate(valid => {
            if (valid) {
              getDept(this.form.cmsCategory).then(response => {
                this.form.cmsCategory = response.data;
              if (this.form.id != undefined) {
                updateConfig(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                addConfig(this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            })
            }
          });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const configIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + configIds + '"的数据项？').then(function() {
          return delConfig(configIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('api/system/sa/export', {
        ...this.queryParams
      }, `文章管理.xlsx`)
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    }
  }
};
</script>
<style scoped>
.mr10{
  margin-right: 10px;
}

.mb8{
  margin-bottom: 8px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
